package com.berry.common;

import java.security.Key;
import java.security.SecureRandom;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;

import org.apache.commons.codec.binary.Base64;

public class DESUtils {
	private static Key key;
	private static String KEY_STR = "3322253";
	static{
		try {
			KeyGenerator generator = KeyGenerator.getInstance("DES");
			generator.init(new SecureRandom(KEY_STR.getBytes()));
			key = generator.generateKey();
			generator = null;
		} catch (Exception e) {
			throw new RuntimeException();
		}
	}
	
	public static String getEncryptString(String str){
		Base64 base64 = new Base64();
		try {
			byte [] strBytes = str.getBytes("UTF8");
			Cipher cipher = Cipher.getInstance("DES");
			cipher.init(Cipher.ENCRYPT_MODE, key);
			byte [] encryptStrBytes = cipher.doFinal(strBytes);
			return new String(base64.encode(encryptStrBytes),"UTF8");
		} catch (Exception e) {
			throw new RuntimeException();
		}
	}
	
	public static String getDecryptString(String str){
		try {
			byte[] strBytes = Base64.decodeBase64(str.getBytes());
			Cipher cipher = Cipher.getInstance("DES");
			cipher.init(Cipher.DECRYPT_MODE, key);
			byte[] decryptBytes = cipher.doFinal(strBytes);
			return new String(decryptBytes,"UTF8");
		} catch (Exception e) {
			throw new RuntimeException();
		}
	}
	
	public static void main(String[] args) {
		System.out.println("加密："+"e2003412012ef6000d57");
		String cryptStr = getEncryptString("e2003412012ef6000d57");
		System.out.println("加密后: "+ cryptStr);
		System.out.println("解密: "+getDecryptString(cryptStr));
	}
}
